package com.hzj.controller.api;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzj.exception.HospitalException;
import com.hzj.pojo.OrderInfo;
import com.hzj.pojo.PaymentInfo;
import com.hzj.pojo.RefundInfo;
import com.hzj.pojo.UserInfo;
import com.hzj.pojo.vo.user.OrderCountQueryVo;
import com.hzj.service.OrderInfoService;
import com.hzj.service.PaymentInfoService;
import com.hzj.service.RefundInfoService;
import com.hzj.service.UserLoginRecordService;
import com.hzj.utils.IPUtils;
import com.hzj.utils.RedisUtil;
import com.hzj.utils.Result;
import com.hzj.utils.ResultCodeEnum;
import io.swagger.models.auth.In;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/atformapi/order/orderInfo")
public class ApiOrderController {
    @Autowired
    OrderInfoService ois;
    @Autowired
    PaymentInfoService pis;
    @Autowired
    RefundInfoService ris;
    @Autowired
    RedisUtil redisUtil;


    /**
     * 排班编号与就诊人id查询orderinfo的id
     */

    @PostMapping("/auth/submitOrder/{scheduleId}/{patientId}")
    public Result queryByScheduleIdPatientId(@PathVariable String scheduleId, @PathVariable Long patientId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("hos_schedule_id", scheduleId);
        map.put("patient_id", patientId);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.allEq(map);
        OrderInfo orderInfo = ois.getOne(wrapper);
        Long id = orderInfo.getId();
        return Result.ok(id);
    }

    /**
     * 查询订单表
     *
     * @return
     */
    @PostMapping("/auth/getStatusList")
    public Result queryOrderInfo() {
        List<OrderInfo> orderInfoList = ois.list(null);
        return Result.ok(orderInfoList);
    }

    /**
     * 根据page, limit、searchObj:patientId、orderStatus
     */

    @PostMapping("/auth/{page}/{limit}")
    public Result queryByPageLimit(@PathVariable int page, @PathVariable int limit, @RequestParam(required = false) Long patientId, @RequestParam(required = false) Integer orderStatus, HttpServletRequest request) {
        IPage iPage = new Page(page, limit);
        System.out.println("ip地址---："+IPUtils.getIpAddr(request));
        UserInfo userInfo= (UserInfo) redisUtil.get("userInfo"+ IPUtils.getIpAddr(request));
        Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtils.isEmpty(patientId)) {
            map.put("patient_id", patientId);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            map.put("order_status", orderStatus);
        }
        map.put("user_id",userInfo.getId());
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.allEq(map);
        IPage iPage1 = ois.page(iPage, wrapper);
        System.out.println("----订单-----"+iPage1.getRecords());
        return Result.ok(iPage1);
    }


    /**
     * 根据id查询
     */
    @PostMapping("/auth/getOrderInfo/{orderId}")
    public OrderInfo queryById(@PathVariable Long orderId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", orderId);
        List<OrderInfo> list = ois.list(wrapper);
        return list.get(0);
    }

    /**
     * 根据id删除
     */
    @PostMapping("/auth/cancelOrder/{orderId}")
    public Result updateById(@PathVariable Long orderId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", orderId);
        boolean remove = ois.remove(wrapper);
        if (!remove) {
            throw new HospitalException(ResultCodeEnum.FAIL);
        }
        return Result.ok();
    }


    /**
     * 修改or添加订单
     *
     * @return
     */
    @PostMapping("/updateOrderInfo")
    public Result updateOrderInfo(@RequestBody OrderInfo orderInfo) {
        boolean b = ois.updateOrderInfo(orderInfo);
        if (!b) {
            throw new HospitalException(ResultCodeEnum.FAIL);
        }
        return Result.ok();
    }

    /**
     * 删除订单
     *
     * @return
     */
    @PostMapping("/deleteOrderInfo")
    public Result deleteOrderInfo(@PathVariable String outTradeNo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("outTradeNo", outTradeNo);
        boolean b = ois.remove(wrapper);
        if (!b) {
            throw new HospitalException(ResultCodeEnum.FAIL);
        }
        return Result.ok();
    }

    /**
     * 查询支付表
     */
    @PostMapping("/queryPaymentInfo")
    public Result queryPaymentInfo() {
        List<PaymentInfo> paymentInfoList = pis.list(null);
        return Result.ok(paymentInfoList);
    }

    /**
     * 修改OR添加支付表
     */
    @PostMapping("/updatePaymentInfo")
    public Result updatePaymentInfo(@RequestBody PaymentInfo paymentInfo) {
        boolean b = pis.save(paymentInfo);
        if (!b) {
            throw new HospitalException(ResultCodeEnum.FAIL);
        }
        return Result.ok();
    }

    /**
     * 删除支付表
     */
    @PostMapping("/deletePaymentInfo/{outTradeNo}")
    public Result deletePaymentInfo(@PathVariable String outTradeNo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("out_trade_no", outTradeNo);
        boolean b = pis.remove(wrapper);
        if (!b) {
            throw new HospitalException(ResultCodeEnum.FAIL);
        }
        return Result.ok(1);
    }

    /**
     * 查询退款表
     */
    @PostMapping("/queryRefundInfo")
    public Result queryRefundInfo() {
        List<RefundInfo> refundInfoList = ris.list(null);
        return Result.ok(refundInfoList);
    }

    /**
     * 添加退款表
     */
    @PostMapping("/updateRefundInfo")
    public Result updateRefundInfo(@RequestBody RefundInfo refundInfo) {
        System.out.println("退款");
        boolean b = ris.save(refundInfo);
        System.out.println("退款返回值:" + b);
        if (!b) {
            throw new HospitalException(ResultCodeEnum.FAIL);
        }
        return Result.ok();
    }

    /**
     * 删除退款表
     */
    @PostMapping("/deleteRefundInfo/{outTradeNo}")
    public Result deleteRefundInfo(@PathVariable String outTradeNo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("out_trade_no", outTradeNo);
        boolean b = ris.remove(wrapper);
        if (!b) {
            throw new HospitalException(ResultCodeEnum.FAIL);
        }
        return Result.ok();
    }

    @PostMapping("/auth/saveOrderInfo")
    boolean saveOrderInfo(@RequestBody OrderInfo orderInfo) {
        return ois.save(orderInfo);
    }



    @PostMapping("/auth/updateOrderByHosRecordId")
    boolean updateOrderByHosRecordId(@RequestBody OrderInfo orderInfo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", orderInfo.getId());
        return ois.update(orderInfo, wrapper);
    }

    /**
     * 使用rabbit
     * @param orderInfo
     * @return
     */
    @RabbitListener(queues = {"Fanout.queue.updateOrderByHosRecordIdQueue"})
    void updateOrderByHosRecordIdRabbitMq(String orderInfo) {
        System.out.println("~~~~~~执行rabbit：updateOrderByHosRecordIdRabbitMq");
        OrderInfo orderInfo1 = JSONObject.parseObject(orderInfo, OrderInfo.class);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", orderInfo1.getId());

        ois.update(orderInfo1, wrapper);
    }

    @PostMapping("auth/queryAll/{page}/{limit}")
    public Result queryAll(@PathVariable int page, @PathVariable int limit, @RequestParam(required = false) String patientName, @RequestParam(required = false) String hosname) {
        IPage iPage = new Page(page, limit);
        QueryWrapper wrapper = new QueryWrapper();
        if (StringUtils.isEmpty(patientName) && StringUtils.isEmpty(hosname)) {
            iPage = ois.page(iPage);

            return Result.ok(iPage);
        }

        if (!StringUtils.isEmpty(patientName)) {
            wrapper.like("patient_name", patientName);
        }
        if (!StringUtils.isEmpty(hosname)) {
            wrapper.like("hosname", hosname);
        }
        iPage = ois.page(iPage, wrapper);


        return Result.ok(iPage);
    }

    @PostMapping("/querPaymentInfoByOrderId/{orderId}")
    public PaymentInfo querPaymentInfoByOrderId(@PathVariable Integer orderId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("order_id", orderId);
        return pis.getOne(wrapper);
    }

    @PostMapping("querRefundInfoByOrderId/{orderId}")
    public RefundInfo querRefundInfoByOrderId(@PathVariable Integer orderId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("order_id", orderId);
        return ris.getOne(wrapper);
    }

    //下面是黄艳写的:
    //1.查询预约订单所有记录数 返回json数据:
    @PostMapping("selectCountOne")
    public Integer selectCountOne() {

        int num1 = ois.selectCount();

        return num1;
    }

    @PostMapping("selectCountTwo")
    public Integer selectCountTwo() {
        int num2 = pis.selectCount();
        return num2;
    }

    @PostMapping("selectCountThree")
    public Integer selectCountThree() {
        int num3 = ris.selectCount();
        return num3;
    }

    @PostMapping("inner/getCountMap")
    public Map<String, Object> getCountMap(@RequestBody OrderCountQueryVo orderCountQueryVo) {
        return ois.getCountMap(orderCountQueryVo);
    }

    /**
     * 使用rabbit
     *
     * @param orderInfo
     * @return
     */
    @RabbitListener(queues = {"Fanout.queue.saveOrderInfoQueue"})
    void saveOrderInfoRabbitMq(String orderInfo) {
        System.out.println("~~~~~~执行rabbit：saveOrderInfoRabbitMq:" + orderInfo);
        OrderInfo info = JSONObject.parseObject(orderInfo, OrderInfo.class);
        System.out.println("对象值："+info.getId());
        ois.save(info);
    }
}
